//
//  LBMComposeView.swift
//  微博
//
//  Created by 刘保满 on 16/5/28.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SnapKit

class LBMComposeView: UIView {
    
    
    //定义数组保存按钮
    private lazy var buttons: [LBMComposeButton] = [LBMComposeButton]()
    
    //会造成循环引用,所以用weak
    weak var target: UIViewController?
    
    func show(targetVC target: UIViewController) {
        
        self.target = target
        
        //添加视图
        target.view.addSubview(self)
        
    }
    
    
    
    
    override init(frame: CGRect) {
        let rect = UIScreen.mainScreen().bounds
        super.init(frame: rect)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //将要移动到父视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(superview)
        //要呈现动画,从刚创建的开始按顺序动画处理
        for (index,btn) in buttons.enumerate() {
            startAnimation(btn, index: index, offset: -350)
            
        }
        
    }
    
    
    //点击屏幕时,从父视图上移除,要呈现动画
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //倒序呈动画移除
        for (index,btn) in buttons.reverse().enumerate() {
            
            startAnimation(btn, index: index, offset: 350)
        }
        
    }
    
    
    //封装按钮动画的方法
    private func startAnimation(btn: LBMComposeButton, index: Int, offset: CGFloat) {
        
        UIView.animateWithDuration(0.8, delay: Double(index) * 0.02, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: {
            
            btn.center = CGPoint(x: btn.center.x, y: btn.center.y + offset)
            
            
        }) { (_) in
            
            if offset > 0 {
                
                //移除
                self.removeFromSuperview()
            }
            
        }
        
    }
    
    
    //设置UI
    private func setupUI() {
        
        backgroundColor = UIColor.redColor()
        //添加子控件
        addSubview(backImageView)
        addSubview(sloganImageView)
        
        
        //设置约束
        sloganImageView.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
            
        }
        
        //添加按钮
        addChildButtons()
        
        
    }
    
    //创建按钮
    private func addChildButtons() {
        
        let count = composeItems.count
        
        let w: CGFloat = 80
        let h: CGFloat = 120
        
        let margin: CGFloat = (ScreenWidth - 3*w) / 4
        
        for i in 0..<count {
            
            let btn = LBMComposeButton()
            
            let item = composeItems[i]
            
            btn.composeItem = item
            
            //添加点击事件
            btn.addTarget(self, action: #selector(LBMComposeView.btnDidClick(_:)), forControlEvents: .TouchUpInside)
            
            
            //frame
            //行
            let row = i / 3
            let col = i % 3
            let x = CGFloat(col) * (margin + w) + margin
            
            //这样是看不到按钮的 要-350
            let y = CGFloat(row) * (h + margin) + ScreenHeight
            
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            
            self.addSubview(btn)
            
            //把创建的按钮添加到数组中
            buttons.append(btn)
            
        }
        
    }
    
    //按钮点击事件,被点击的按钮变大,其他的变小
    @objc private func btnDidClick(btn: LBMComposeButton) {
        
        //        print("asdfsdf")
        for button in buttons {
            
            var scale: CGFloat = 0
            
            if button == btn {
                //是被点击的按钮
                //变大
                scale = 2.0
                
            } else {
                //缩小
                scale = 0.2
            }
            
            UIView.animateWithDuration(0.25, animations: {
                button.alpha = 0
                button.transform = CGAffineTransformMakeScale(scale, scale)
                }, completion: { (_) in
                    
            })
        }
        
        //跳转界面
        print(btn.composeItem)
        //在plist 文件中添加了target
        guard let target = btn.composeItem?.target else {
            return
            
        }
        let type = NSClassFromString(target) as! UIViewController.Type
        //        print(type)
        //type   LBMComposeViewController
        let vc = type.init()
        
        let nav = UINavigationController(rootViewController: vc)
        
        //跳转
        //从上面可以show方法可以得到MainView控制器
        self.target?.presentViewController(nav, animated: true, completion: {
            
            //移除
            self.removeFromSuperview()
            
        })
        
    }
    
    
    //懒加载子控件
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage.snapShotCurrentWindow().applyLightEffect())
    
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    private lazy var composeItems: [LBMComposeItem] = {
        
        var array = [LBMComposeItem]()
        //获取文件路径
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)!
        
        ///读取数据
        let itemArray = NSArray(contentsOfFile: path) as! [[String: AnyObject]]
        
        //遍历数组字典转模型
        for item in itemArray {
            
            let composeItem = LBMComposeItem(dict: item)
            array.append(composeItem)
        }
        
        return array
    }()
    
}
